package com.mars.algorithm;

/**
 * 基于数组实现的可动态扩展的栈
 *
 * @Author King
 * @create 2020/6/30 14:35
 */
public class KingArrayStack<T> {

    private T[] data;
    private int size;
    private int count;


    public KingArrayStack() {
        this.size = 4;
        this.count = 0;
        this.data = (T[]) new Object[size];
    }

    public KingArrayStack(int size) {
        this.size = size;
        this.count = 0;
        this.data = (T[]) new Object[size];
    }

    public boolean push(T t) {
        if (count == size) {
            //实现动态扩容
            this.size = size * 2;
            T[] tmp = (T[]) new Object[size];
            for (int i = 0; i < (this.size / 2); i++) {
                tmp[i] = this.data[i];
            }
            //清空数组
            this.data = null;
            //重新指向新的数组对象地址
            this.data = tmp;
        }
        this.data[count] = t;
        ++count;
        return true;
    }

    public T poll() {
        if (count == 0) {
            return null;
        }
        T tmp = this.data[count - 1];
        --count;
        return tmp;
    }

    public int size() {
        return this.size;
    }

    public static void main(String[] args) {
        KingArrayStack<String> stack = new KingArrayStack<String>();
        stack.push("1");
        stack.push("2");
        stack.push("3");
        stack.push("4");
        stack.push("5");
        stack.push("6");
        stack.push("7");
        stack.push("8");
        stack.push("9");
        stack.push("10");
        stack.push("11");
        stack.push("12");
        stack.push("13");
        stack.push("14");
        stack.push("15");
        stack.push("16");
        stack.push("17");
        for (int i = 0; i < 17; i++) {
            System.out.println(stack.poll());
        }
        System.out.println(stack.size());
    }
}
